﻿using System;
using System.Linq;
using System.Web.Mvc;
using MvcPagingExample.Models;

namespace MvcPagingExample
{
	public class PagingAttribute:  ActionFilterAttribute
	{
		public int PageSize { get; set; }

		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			var paging = filterContext.ActionParameters.Select(p => p.Value as PagingViewModel).Where(f=> f !=null).FirstOrDefault();

			if (paging != null)
			{
				paging.PageSize = PageSize;

				filterContext.RouteData.Values.Add("PageSize", this.PageSize);

				if (paging.PageNumber == 0)
				{
					filterContext.RouteData.Values.Add("PageNumber", 1);
					paging.PageNumber = 1;
				}
			}

			base.OnActionExecuting(filterContext);
		}

		public override void OnActionExecuted(ActionExecutedContext filterContext)
		{
			var model = filterContext.Controller.ViewData.Model as IItemListInfo;

			if (filterContext.HttpContext.Request.IsAjaxRequest())
			{
				ViewResult result = filterContext.Result as ViewResult;
				filterContext.Result = new PartialViewResult() { TempData = result.TempData, View=result.View, ViewData=result.ViewData, ViewEngineCollection=result.ViewEngineCollection};
			}
						

			if (model != null)
			{
				filterContext.RouteData.Values.Add("Pages", (int) Math.Ceiling( (double) model.TotalItems/this.PageSize));
			}

			base.OnActionExecuted(filterContext);
		}
	}
}